package com.food.restaurantpro.fragments;

import java.util.Observable;
import java.util.Observer;

import com.food.restaurantpro.R;
import com.food.restaurantpro.RestaurantApp;
import com.food.restaurantpro.activity.MainActivity;
import com.food.restaurantpro.connection.DataHelper;
import com.food.restaurantpro.connection.DataResult;
import com.food.restaurantpro.connection.IServerService.Methods;
import com.food.restaurantpro.database.tables.ReservationTable;
import com.food.restaurantpro.objects.Reservation;
import com.food.restaurantpro.utils.Utils;

import android.app.AlertDialog;
import android.app.DatePickerDialog;
import android.app.TimePickerDialog;
import android.app.TimePickerDialog.OnTimeSetListener;
import android.content.DialogInterface;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.text.format.DateFormat;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.DatePicker;
import android.widget.TextView;
import android.widget.TimePicker;

public class EditReservationFragment extends Fragment implements OnClickListener {
	
	private TextView tvHeader;
	private TextView mTvDate;
	private TextView mTvTime;
	private TextView mTvPeoples;
	private boolean isProcessSubmit = false;
	private Reservation mReservation;
	
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		View view = inflater.inflate(R.layout.fragment_edit_reservation, container, false);
		
		tvHeader = (TextView) view.findViewById(R.id.tvHeader);
		if(tvHeader != null) {
			tvHeader.setText(R.string.reservation);
		}
		mTvDate = (TextView) view.findViewById(R.id.tvDateReservation);
		view.findViewById(R.id.btnEditDateReservation).setOnClickListener(this);
		mTvTime = (TextView) view.findViewById(R.id.tvTimeReservation);
		view.findViewById(R.id.btnEditTimeReservation).setOnClickListener(this);
		mTvPeoples = (TextView) view.findViewById(R.id.tvPeopleReservation);
		view.findViewById(R.id.btnEditPeopleReservation).setOnClickListener(this);
		
		String memberCode = "anomynous";
		if(RestaurantApp.userInfo != null && !Utils.isEmpty(RestaurantApp.userInfo.getGenerateId())) {
			memberCode = RestaurantApp.userInfo.getGenerateId();
		}
		
		view.findViewById(R.id.tvReservationSubmit).setOnClickListener(this);
		view.findViewById(R.id.btnSubmitReservation).setOnClickListener(this);
		view.findViewById(R.id.tvReservationCancel).setOnClickListener(this);
		view.findViewById(R.id.btnCancelReservation).setOnClickListener(this);
		mTvDate.setText(mReservation.getReservationDate());
		mTvTime.setText(mReservation.getReservationTime());
		mTvPeoples.setText(mReservation.getReservationNumber());

		mTvDate.setOnClickListener(this);
		mTvTime.setOnClickListener(this);
		mTvPeoples.setOnClickListener(this);
		return view;
	}
	
	@Override
	public void onDestroy() {
		// TODO delete image and cache de giai phong bo nho
		super.onDestroy();
		Runtime.getRuntime().gc();
	}


	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.tvDateReservation:
		case R.id.btnEditDateReservation:
			showDialogSelectDate();
			break;
		case R.id.tvTimeReservation:
		case R.id.btnEditTimeReservation:
			showDialogSelectTime();
			break;
		case R.id.tvPeopleReservation:
		case R.id.btnEditPeopleReservation:
			showDialogSelectPeople();
			break;
		case R.id.tvReservationSubmit:
		case R.id.btnSubmitReservation:
			updateReservation();
			break;
		case R.id.tvReservationCancel:
		case R.id.btnCancelReservation:
			((MainActivity)getActivity()).showNextReservationFragment();
			break;
		default:
			break;
		}
	}
	
	private void updateReservation() {
		if(isProcessSubmit) {
			return;
		}
		isProcessSubmit = true;
		mReservation.setReservationDate(mTvDate.getText().toString());
		mReservation.setReservationTime(mTvTime.getText().toString());
		mReservation.setReservationNumber(mTvPeoples.getText().toString().split(" ")[0]);
		mReservation.setReservationStatus("1");
		if(!Utils.isEmpty(RestaurantApp.userInfo.getGenerateId())) {
			mReservation.setReservationMemberCode(RestaurantApp.userInfo.getGenerateId());
		} else {
			mReservation.setReservationMemberCode("anomynous");
		}
		DataHelper.getInstance().addObserver(new Observer() {
			@Override
			public void update(Observable observable, Object data) {
				// TODO Auto-generated method stub
				DataResult result = (DataResult) data;
				if (result.getMethodName().equals(Methods.updateReservation)) {
					((MainActivity)getActivity()).hideProcessDialog();
					String status = (String) result.getData();
					if(!Utils.isEmpty(status) && status.equals("true")) {
						Utils.showToast("Update succesfull");
						ReservationTable.updateReservationByID(mReservation);
						((MainActivity)getActivity()).showNextReservationFragment();
					} else {
						Utils.showToast("Update fail");
					}
					isProcessSubmit = false;
					DataHelper.getInstance().deleteObserver(this);
				}
			}
		});
		((MainActivity)getActivity()).showProcessDialog();
		DataHelper.getInstance().updateReservation(mReservation);
	}
	
	private void showDialogSelectPeople() {
		AlertDialog.Builder builderSingle = new AlertDialog.Builder(
                getActivity());
        builderSingle.setIcon(R.drawable.phonatic_logo);
        builderSingle.setTitle("Select number people");
        final ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(
                getActivity(),
                android.R.layout.select_dialog_singlechoice);
        for(int i = 1; i < 11; i++) {
        	arrayAdapter.add("" + i);
        }
        builderSingle.setNegativeButton(getActivity().getString(R.string.cancel),
                new DialogInterface.OnClickListener() {

                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                    }
                });

        builderSingle.setAdapter(arrayAdapter,
                new DialogInterface.OnClickListener() {

                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        mTvPeoples.setText(arrayAdapter.getItem(which));
                    }
                });
        builderSingle.show();
	}

	private void showDialogSelectTime() {
		new TimePickerDialog(getActivity(), timePickerListener, 8, 8, DateFormat.is24HourFormat(getActivity())).show();
	}

	private void showDialogSelectDate() {
		new DatePickerDialog(getActivity(), datePickerListener, 2013, 10, 10).show();
	}
	
	private TimePickerDialog.OnTimeSetListener timePickerListener = new OnTimeSetListener() {
		@Override
		public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
			mTvTime.setText(Utils.getStandardTime(hourOfDay, minute));
		}
	};

	private DatePickerDialog.OnDateSetListener datePickerListener = new DatePickerDialog.OnDateSetListener() {
		public void onDateSet(DatePicker view, int selectedYear,int selectedMonth, int selectedDay) {
			mTvDate.setText(Utils.getStandardDate(selectedDay, selectedMonth + 1, selectedYear));
		}
	};

	public void setReservation(Reservation reservation) {
		mReservation = reservation;
	}
}
